﻿using MediatR;
using SheepCultivation.API.AddliCation.BuildingD;
using SheepCultivation.Common.Domain.Sheep;
using SheepCultivation.Common.Domain.SheepBasicInformation;
using SheepCultivation.Common.Domain.Week2;
using SheepCultivation.Common.Domain.Week3;
using SheepCultivation.Common.Dto;
using SheepCultivation.Common.Infrastructure.Interface;
using SheepCultivation.Enum;
using System;
using System.Xml;
using static System.Runtime.InteropServices.JavaScript.JSType;

namespace SheepCultivation.API.AddliCation.SheepManagement
{
    public class DeathManagementSeachHandler : IRequestHandler<DeathManagementSeachCommon, Result>
    {
        #region 仓储
        /// <summary>
        /// 羊只死亡仓储
        /// </summary>
        public readonly IBaseRepository<DeathManagement> DeathManagementRepository;
        /// <summary>
        /// 羊只淘汰仓储
        /// </summary>
        public readonly IBaseRepository<Eliminates> EliminatesRepository;
        /// <summary>
        /// 羊只类型仓储
        /// </summary>
        public readonly IBaseRepository<SheepTypes> SheepTypesRepository;
        /// <summary>
        /// 栋舍仓储
        /// </summary>
        public readonly IBaseRepository<Building> BuildingRepository;
        /// <summary>
        /// 栏位仓储
        /// </summary>
        public readonly IBaseRepository<Columns> ColumnsRepository;
        /// <summary>
        /// 品种仓储 
        /// </summary>
        public readonly IBaseRepository<Sheepvariety> SheepvarietyRepository;
        /// <summary>
        /// 种母配种仓储
        /// </summary>
        public readonly IBaseRepository<SheepHybridization> SheepHybridizationRepository;
        /// <summary>
        /// 出生信息仓储
        /// </summary>
        public readonly IBaseRepository<BirthMessage> BirthMessageRepository;
        /// <summary>
        /// 基本信息仓储
        /// </summary>
        public readonly IBaseRepository<BasicInformation> BasicInformationRepository;
        /// <summary>
        /// 日志
        /// </summary>
        public readonly ILogger<DeathManagementSeachHandler> logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="deathManagementRepository">羊只死亡</param>
        /// <param name="EliminatesRepository">羊只淘汰</param>
        /// <param name="SheepTypesRepository">羊只类型</param>
        /// <param name="BuildingRepository">栋舍</param>
        /// <param name="ColumnsRepository">栏位</param>
        /// <param name="SheepvarietyRepository">品种</param>
        /// <param name="SheepHybridizationRepository">种母配种</param>
        /// <param name="BirthMessageRepository">出生信息</param>
        /// <param name="BasicInformationRepository">基本信息</param>
        /// <param name="logger">日志</param>
        public DeathManagementSeachHandler(IBaseRepository<DeathManagement> deathManagementRepository, IBaseRepository<Eliminates> EliminatesRepository, IBaseRepository<SheepTypes> SheepTypesRepository, IBaseRepository<Building> BuildingRepository, IBaseRepository<Columns> ColumnsRepository, IBaseRepository<Sheepvariety> SheepvarietyRepository, IBaseRepository<SheepHybridization> SheepHybridizationRepository, IBaseRepository<BirthMessage> BirthMessageRepository, IBaseRepository<BasicInformation> BasicInformationRepository, ILogger<DeathManagementSeachHandler> logger)
        {
            DeathManagementRepository = deathManagementRepository;
            this.EliminatesRepository = EliminatesRepository;
            this.SheepTypesRepository = SheepTypesRepository;
            this.BuildingRepository = BuildingRepository;
            this.ColumnsRepository = ColumnsRepository;
            this.SheepvarietyRepository = SheepvarietyRepository;
            this.SheepHybridizationRepository = SheepHybridizationRepository;
            this.BirthMessageRepository = BirthMessageRepository;
            this.BasicInformationRepository = BasicInformationRepository;
            this.logger = logger;
        }
        #endregion

        #region 羊只死亡列表
        /// <summary>
        /// 羊只死亡列表
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Result> Handle(DeathManagementSeachCommon request, CancellationToken cancellationToken)
        {
            var result = new Result() { Code = (int)CommonEnumCode.error };
            //异常处理
            try
            {
                logger.LogInformation("羊只死亡列表显示成功!");
                var data = new pageAll() { };
                var list = (from a in DeathManagementRepository.GetAll() //羊只死亡
                            join b in BuildingRepository.GetAll() on a.BuildingId equals b.BuildingId //栋舍
                            join c in ColumnsRepository.GetAll() on a.ColumnsId equals c.ColumnsId    //栏位
                            join d in SheepvarietyRepository.GetAll() on a.SheepvarietyId equals d.SheepvarietyId //品种
                            join e in SheepHybridizationRepository.GetAll() on a.SheepHybridizationId equals e.SheepHybridizationId   //种母配种
                            join f in BirthMessageRepository.GetAll() on a.BreedingSheepArchiveId equals f.BreedingSheepArchiveId     //出生信息
                            join g in BasicInformationRepository.GetAll() on f.BreedingSheepArchiveId equals g.BreedingSheepArchiveId //基本信息
                            select new DeathManagementDto()
                            {
                                //羊只死亡
                                DeathManagementId = a.DeathManagementId,
                                DeathType = a.DeathType,
                                //Sexs = a.Sexs,
                                DeathTime = a.DeathTime,
                                Numberes = a.Numberes,
                                DeathManagementRemark = a.DeathManagementRemark,
                                //栋舍
                                BuildingId = b.BuildingId,
                                BuildingName = b.BuildingName,
                                //栏位
                                ColumnsId = c.ColumnsId,
                                ColumnsName = c.ColumnsName,
                                //品种
                                SheepvarietyId = d.SheepvarietyId,
                                SheepvarietyName = d.SheepvarietyName,
                                //种母配种
                                SheepHybridizationId = e.SheepHybridizationId,
                                SheepHybridizationReceiptNumber = e.SheepHybridizationReceiptNumber,
                                SheepHybridizationSerialNumber = e.SheepHybridizationSerialNumber,
                                BreedState = e.BreedState,
                                //出生信息
                                BirthMessageId = f.BirthMessageId,
                                BirthDate = f.BirthDate,
                                //基本信息（羊只耳号）
                                BreedingSheepArchiveId = g.BreedingSheepArchiveId,
                                Auricle = g.Auricle,
                                SheepSex = g.SheepSex,
                            }).ToList();

                //查询条件：死亡开始日期 死亡结束日期 羊只耳号  死亡原因（下拉框）
                if (!string.IsNullOrEmpty(request.beginDate))
                {
                    list = list.Where(x => x.DeathTime >= DateTime.Parse(request.beginDate)).ToList();
                }
                if (!string.IsNullOrEmpty(request.endsDate))
                {
                    list = list.Where(x => x.DeathTime <= DateTime.Parse(request.endsDate).AddDays(1)).ToList();
                }
                if (!string.IsNullOrEmpty(request.auricle))
                {
                    list = list.Where(x => x.Auricle.Contains(request.auricle)).ToList();
                }
                if (request.deathType > 0)
                {
                    list = list.Where(x => x.DeathType == request.deathType).ToList();
                }

                //分页
                data.totalCount = list.Count();
                data.pageCount = (int)Math.Ceiling((list.Count() * 1.0) / request.pageSize);
                data.data = list.OrderBy(x => x.DeathManagementId).Skip((request.pageIndex - 1) * request.pageSize).Take(request.pageSize).ToList();

                result.Code = (int)CommonEnumCode.success;
                result.Data = data;
                result.Msg = "羊只死亡列表显示成功";
            }
            catch (Exception ex)
            {
                logger.LogError("羊只死亡列表显示失败!" + ex.Message);
                result.Msg = "羊只死亡列表显示失败";
            }
            return result;
        }
        #endregion
    }

    /// <summary>
    /// 分页
    /// </summary>
    public class pageAll()
    {
        public int totalCount { get; set; }
        public int pageCount { get; set; }
        public List<DeathManagementDto> data { get; set; }
    }

    public class DeathManagementDto()
    {
        /// <summary>
        /// 死亡管理ID
        /// </summary>
        public int DeathManagementId { get; set; }
        /// <summary>
        /// 死亡原因（下拉框）
        /// </summary>
        public int DeathType { get; set; }
        /// <summary>
        /// 性别
        /// </summary>
        public int Sexs { get; set; }
        /// <summary>
        /// 死亡时间
        /// </summary>
        public DateTime DeathTime { get; set; }
        /// <summary>
        /// 单据号
        /// </summary>
        public string? Numberes { get; set; }
        /// <summary>
        /// 备注
        /// </summary>
        public string? DeathManagementRemark { get; set; }
        ///// <summary>
        ///// 羊只类型ID
        ///// </summary>
        //public int SheepTypesId { get; set; }
        ///// <summary>
        ///// 羊只类型名称 1：种母 2：种公 3：后裔
        ///// </summary>
        //public string? SheepTypesName { get; set; }
        /// <summary>
        /// 栋舍Id
        /// </summary>
        public int BuildingId { get; set; }
        /// <summary>
        /// 栋舍名称
        /// </summary>
        public string? BuildingName { get; set; }
        /// <summary>
        /// 栏位Id
        /// </summary>
        public int ColumnsId { get; set; }
        /// <summary>
        /// 栏位名称
        /// </summary>
        public string? ColumnsName { get; set; }
        /// <summary>
        /// 品种Id
        /// </summary>
        public int SheepvarietyId { get; set; }
        /// <summary>
        /// 品种名称
        /// </summary>
        public string? SheepvarietyName { get; set; }
        /// <summary>
        /// 种母分配Id
        /// </summary>
        public int SheepHybridizationId { get; set; }
        /// <summary>
        /// 单据号
        /// </summary>
        public string? SheepHybridizationReceiptNumber { get; set; }
        /// <summary>
        /// 流水号
        /// </summary>
        public string? SheepHybridizationSerialNumber { get; set; }
        /// <summary>
        /// 繁殖状态
        /// </summary>
        public string? BreedState { get; set; }
        /// <summary>
        /// 出生信息Id
        /// </summary>
        public int BirthMessageId { get; set; }
        /// <summary>
        /// 出生日期
        /// </summary>
        public DateTime BirthDate { get; set; }
        /// <summary>
        /// 羊只耳号Id
        /// </summary>
        public int BreedingSheepArchiveId { get; set; }
        /// <summary> 
        /// 耳号
        /// </summary>
        public string Auricle { get; set; }
        /// <summary>
        /// 性别
        /// </summary>
        public int SheepSex { get; set; }
    }
}
